<template>
  <BaseDialog
    ref="baseDialog"
    :title="isEdit ? '编辑文件' : '新增文件'"
    @confrim="confrim"
    @cancel="close"
  >
    <BaseForm
      labelWidth="150px"
      :fromIems="fromIems"
      :size="'medium'"
      ref="BaseForm"
      @submit="submit"
      @edit="edit"
    >
      <template #devices>
        <div>
          <el-tag
            v-for="(item, index) in devices"
            :key="item"
            closable
            @close="handlDel(index)"
            >{{ item }}</el-tag
          >
        </div>
        <el-button type="primary" @click="handleopen">选择设备</el-button>
      </template>
    </BaseForm>

    <Devices ref="Devices" @select="select"></Devices>
  </BaseDialog>
</template>

<script>
import { Message } from "element-ui";
import { uploadImg, searchFormParams } from "@/utils";
import { editOtaFile, addOtaFile, getDeviceModels } from "@/api/device";
import Devices from "./devices.vue";
export default {
  components: {
    Devices,
  },
  data() {
    return {
      title: "",
      fromIems: [
        {
          valueType: "img",
          label: "上传文件",
          dataIndex: "id",
          uplaod: (e) => this.handleUpload(e),
          accept: "file/bin",
          rules: [{ required: true, message: "请上传", trigger: "blur" }],
          defaultValue: "",
        },
        {
          valueType: "input",
          label: "文件标题",
          dataIndex: "title",
          rules: [{ required: true, message: "请输入", trigger: "blur" }],
        },
        {
          valueType: "input",
          label: "文件ID",
          dataIndex: "id",
          props: {
            disabled: true,
            style: {
              width: "220px",
            },
          },
          rules: [{ required: true, message: "请输入", trigger: "blur" }],
        },
        {
          valueType: "input",
          label: "文件名",
          dataIndex: "fileName",
          props: {
            disabled: true,
            style: {
              width: "220px",
            },
          },
          rules: [{ required: true, message: "请输入", trigger: "blur" }],
        },

        {
          valueType: "select",
          label: "文件类型",
          dataIndex: "type",
          rules: [{ required: true, message: "请选择", trigger: "blur" }],
          onChange: (e) => this.hanldeChangeType(e),
          options: [
            {
              label: "显示板",
              value: 0,
            },
            {
              label: "XY轴板",
              value: 1,
            },
            {
              label: "驱动板A",
              value: 2,
            },
            {
              label: "驱动板B",
              value: 3,
            },
            {
              label: "驱动板C",
              value: 4,
            },
            {
              label: "驱动板D",
              value: 5,
            },
            {
              label: "合宇",
              value: 9,
            },
          ],
        },
        {
          valueType: "input",
          label: "版本号",
          dataIndex: "ver",
          rules: [{ required: true, message: "请输入", trigger: "blur" }],
        },
        {
          valueType: "select",
          label: "升级条件",
          dataIndex: "otaType",
          rules: [{ required: true, message: "请选择", trigger: "blur" }],
          options: [
            {
              label: "直接升级",
              value: 0,
            },
            {
              label: "需用户确认",
              value: 1,
            },
          ],
        },
        {
          valueType: "select",
          label: "设备型号",
          dataIndex: "models",
          rules: [{ required: true, message: "请选择", trigger: "blur" }],
          props: {
            multiple: true,
            style: {
              width: "220px",
            },
          },
          options: [],
        },
        {
          valueType: "select",
          label: "升级类型",
          dataIndex: "upgradeType",
          rules: [{ required: true, message: "请选择", trigger: "blur" }],
          options: [
            {
              label: "全部",
              value: 1,
            },
            {
              label: "指定",
              value: 2,
            },
          ],
        },
        {
          valueType: "slot",
          label: "设备",
          dataIndex: "dvs",
          defaultValue: "",
          slotName: "devices",
          hide: (row) => row.upgradeType == 1,
          // rules: [{ required: true, message: "请选择", trigger: "blur" }],
        },
      ],
      isEdit: false,
      devices: [],
    };
  },
  methods: {
    open(row) {
      row ? (this.isEdit = true) : (this.isEdit = false);
      this.$refs.baseDialog.open();
      this.handleGetModels(1);
      this.$nextTick(() => {
        if (row) {
          for (var k in row) {
            this.$set(this.$refs.BaseForm.form, k, row[k]);
            if (k === "models") {
              this.$set(
                this.$refs.BaseForm.form,
                "models",
                row.models.split(",")
              );
              // searchFormParams(this, "id").defaultValue = row["id"];
            }
            if (row["upgradeType"] == 2) {
              this.devices = row.dvs.split(",");
            }
          }
        } else {
          this.$refs.BaseForm.form = {};
        }
      });
    },
    // 获取型号
    async handleGetModels(type) {
      //type 1其他 2 合于
      this.fromIems[7].options = [];
      const res = await getDeviceModels({ type: type });
      if (!res.status) {
        res.content.forEach((el) => {
          this.fromIems[7].options.push({
            label: el,
            value: el,
          });
        });
      }
    },
    hanldeChangeType(e) {
      if (e == 9) {
        this.handleGetModels(2);
      } else {
        this.handleGetModels(1);
      }
      this.$set(this.$refs.BaseForm.form, "models", []);
    },
    handleopen() {
      this.$refs.Devices.open();
    },
    select(row) {
      console.log(row);
      if (this.devices.includes(row.imei)) {
        Message.warning("已经存在设备");
        return;
      }
      this.devices.push(row.imei);
    },
    handlDel(index) {
      this.devices.splice(index, 1);
    },
    handleUpload(e) {
      if (e.size > 512 * 1024) {
        Message.error("文件大小不能超过512K");
        return;
      }
      // 读取文件
      const reader = new FileReader();
      reader.readAsArrayBuffer(e);
      reader.onload = (event) => {
        const arrayBuffer = event.target.result;
        const uint8Array = new Uint8Array(arrayBuffer);
        const tenthByte = uint8Array[9];
        const hexValue = tenthByte.toString(16).padStart(2, "0").toUpperCase();
        console.log(hexValue, "xxxxx");
        if (hexValue == "00") {
          this.$set(this.$refs.BaseForm.form, "type", 0);
        } else if (hexValue == "01") {
          this.$set(this.$refs.BaseForm.form, "type", 1);
        } else if (hexValue == "02") {
          this.$set(this.$refs.BaseForm.form, "type", 2);
        } else if (hexValue == "03") {
          this.$set(this.$refs.BaseForm.form, "type", 3);
        } else if (hexValue == "04") {
          this.$set(this.$refs.BaseForm.form, "type", 4);
        } else if (hexValue == "05") {
          this.$set(this.$refs.BaseForm.form, "type", 5);
        } else {
          this.$set(this.$refs.BaseForm.form, "type", 9);
        }
        Message.success("文件读取成功");
      };

      // 读取失败回调
      reader.onerror = () => {
        Message.error("文件读取失败，请重试");
      };

      uploadImg(e, 1024 * 512, {}, "ota", (url, fileName, field) => {
        searchFormParams(this, "id").defaultValue = field;
        searchFormParams(this, "fileName").defaultValue = fileName;
      });
    },
    close() {
      searchFormParams(this, "id").defaultValue = null;
      searchFormParams(this, "fileName").defaultValue = null;
      this.devices = [];
      this.$refs.baseDialog.close();
      this.$refs.BaseForm.rest();
    },
    confrim() {
      if (this.isEdit) {
        this.$refs.BaseForm.edit();
      } else {
        this.$refs.BaseForm.submit();
      }
    },
    async submit(data) {
      let params = { ...data };
      params.state = 0;
      params.models = params.models.join(",");
      if (this.devices.length) {
        params.dvs = this.devices.join(",");
      } else {
        params.dvs = null;
      }
      const res = await addOtaFile(params);
      if (!res.status) {
        this.$emit("success");
        Message.success("success");
        this.close();
      }
    },
    async edit(data) {
      let params = { ...data };
      params.state = 0;
      params.models = params.models.join(",");
      if (this.devices.length) {
        params.dvs = this.devices.join(",");
      } else {
        params.dvs = null;
      }
      const res = await editOtaFile(params);
      if (!res.status) {
        this.$emit("success");
        Message.success("success");
        this.close();
      }
    },
  },
};
</script>

<style lang="scss" scoped></style>
